#include <REGX52.H>
#include "hardware_config.h"

#define BTN_CODE_NONE 0xFF
#define BTN_CODE_START 0
#define BTN_CODE_PAUSE 1
#define BTN_CODE_UP 2
#define BTN_CODE_DOWN 3
#define BTN_CODE_LEFT 4
#define BTN_CODE_RIGHT 5

unsigned int long_press_count = 0;
unsigned int acceleration_count = 0;
#define LONG_PRESS_COUNT_MAX 8
#define ACCELERATION_COUNT_MAX 5
#define ACCELERATION_STEP 4

void delay_ms(unsigned int ms)
{
    unsigned int i, j;
    for (i = 0; i < ms; i++)
    {
        for (j = 0; j < 123; j++)
            ;
    }
}

unsigned char btn_long_press_scan(unsigned char btn_code)
{
    if (long_press_count < LONG_PRESS_COUNT_MAX)
    {
        if (acceleration_count >= ACCELERATION_COUNT_MAX)
        {
            long_press_count += ACCELERATION_STEP;
        }
        else
        {
            long_press_count++;
        }

        delay_ms(1);
        return BTN_CODE_NONE;
    }
    else
    {
        // 持续按下，连续返回n次后，进行加速
        if (acceleration_count < ACCELERATION_COUNT_MAX)
        {
            acceleration_count++;
        }

        long_press_count = 0;
        return btn_code;
    }
}

unsigned char btn_scan()
{
    if (BTN_START == 0)
    {
        delay_ms(20);
        if (BTN_START == 0)
        {
            while (BTN_START == 0)
                ;
            return BTN_CODE_START;
        }
    }

    if (BTN_PAUSE == 0)
    {
        delay_ms(20);
        if (BTN_PAUSE == 0)
        {
            while (BTN_PAUSE == 0)
                ;
            return BTN_CODE_PAUSE;
        }
    }

    if (BTN_UP == 0)
    {
        delay_ms(20);
        if (BTN_UP == 0)
        {
            while (BTN_UP == 0)
                ;
            return BTN_CODE_UP;
        }
    }

    if (BTN_DOWN == 0)
    {
        delay_ms(20);
        if (BTN_DOWN == 0)
        {
            while (BTN_DOWN == 0)
                ;
            return BTN_CODE_DOWN;
        }
    }

    // 实现长按的效果
    // 当按键按下后，每次调用key_scan()
    // LEFT NONE NONE NONE LEFT
    if (BTN_LEFT == 0)
    {
        delay_ms(20);
        if (BTN_LEFT == 0)
        {
            return btn_long_press_scan(BTN_CODE_LEFT);
        }
    }

    if (BTN_RIGHT == 0)
    {
        delay_ms(20);
        if (BTN_RIGHT == 0)
        {
            return btn_long_press_scan(BTN_CODE_RIGHT);
        }
    }

    acceleration_count = 0;
    long_press_count = LONG_PRESS_COUNT_MAX;
    return BTN_CODE_NONE;
}

/**
 * 等待指定的btn_code被按下，否则一直阻塞在这里
 */
void btn_util_press(unsigned char btn_code)
{
    while (btn_scan() != btn_code)
    {
    }
}
